package com.huwaiwai001.producer_consumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产-消费 模型
 * Created by hww on 2019/1/15 5:38 PM.
 */
public class ProducerAndConsumerTest {

    private int count = 0;

    private ReentrantLock lock = new ReentrantLock();

    private Condition notFull = lock.newCondition();

    private Condition notEmpty = lock.newCondition();

    public static void main(String [] args) throws InterruptedException {
        ProducerAndConsumerTest c = new ProducerAndConsumerTest();
        Thread producer = new Thread(() -> {
            try {
                for (;;) {
                    c.doProduct();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread consume = new Thread(() -> {
            try {
                for (int i = 0; i < 20; i++) {
                    c.consume();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        producer.start();
        consume.start();
        Thread.sleep(2000L);
    }

    private void doProduct() throws InterruptedException {
        lock.lock();
        if (count < 10) {
            System.out.println("当前有[" + count + "]个商品,需要生产");
            count++;
            notEmpty.signalAll();
        } else {
            //开始等待未满唤醒
            notFull.await();
        }
        lock.unlock();
    }

    private void consume() throws InterruptedException {
        lock.lock();
        if (count > 0) {
            System.out.println("当前有[" + count + "]个商品,可以消费");
            count--;
            notFull.signalAll();
        } else {
            //开始等待未空唤醒
            notEmpty.await();
        }
        lock.unlock();
    }
}


